package com.pwp.activity;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import xu.ye.bean.ContactBean;
import xu.ye.uitl.BaseIntentUtil;
import xu.ye.view.AddNewActivity;
import xu.ye.view.HomeContactActivity;
import xu.ye.view.sms.MessageBoxList;
import xu.ye.view.ui.QuickAlphabeticBar;

import android.app.AlertDialog;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.net.Uri;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;

import com.agent.crm.base.BaseActivity;
import com.agent.crm.bean.MyContact;
import com.agent.crm.db.DBInitScript;
import com.agent.crm.db.DatabaseManager;
import com.agent.crm.util.DateUtils;
import com.agent.crm.view.MainActivity;
import com.agent.crm.view.NoteBookActivity;
import com.agent.crm.view.R;
import com.agent.crm.view.SearchActivity;

public class ContactAttentionActivity extends BaseActivity{
    private ListView attentionList;
    private List<MyContact> list = new ArrayList<MyContact>();
//    private AttentionAdapter adapter;
    private DatabaseManager manager = null;
    private Button add_contacts;
	private Button title_bt_setting;
	private Button btn_contact;
	private Button btn_carlendar;
	private Button btn_search;
	private Button note_book;
	private Button btn_attention;
	private AttentionAdapter adapter;
	private QuickAlphabeticBar alpha;
	public static final int CONTACT_ADD_EDIT_REQUST_CODE = 40;
	public static final int TASK_ADD_REQUEST_CODE = 4;

    
    private String[] projection = { 
            "contacts_id",
            "name",
            "birth_date",
            "job",
            "address",
            "email",
            "sex",
            "favious",
            "company",
            "remarks",
            "family_phone",
            "office_phone",
            "mobile_phone",
            "sort_key",
            "sys_contactid"
    }; // 查询的列
    
    private void init(){
        SQLiteDatabase database = manager.getWritableDatabase();
        //查询出关注的人
        Cursor cursor = database.query(DBInitScript.Table_ContactsInfo, projection, 
                "is_attention=?", new String[]{"1"}, null, null, null);
        int count = cursor.getCount();
        if(count <= 0 ){
            return;
        }
        for(int i = 0; i < count; i++){
            cursor.moveToPosition(i);
            int contactsId = cursor.getInt(0);
            String name = cursor.getString(1);
            String birthDate = cursor.getString(2);
            String job = cursor.getString(3);
            String address = cursor.getString(4);
            String email = cursor.getString(5);
            String sex = cursor.getString(6);
            String favious = cursor.getString(7);
            String company = cursor.getString(8);
            String remarks = cursor.getString(9);
            String familyPhone = cursor.getString(10);
            String officePhone = cursor.getString(11);
            String mobilePhone = cursor.getString(12);
            String sortKey = cursor.getString(13);
            int sysContactid = cursor.getInt(14);
            MyContact contact = new  MyContact();
            contact.setContactsId(contactsId);
            contact.setName(name);
            contact.setBirthDate(birthDate);
            contact.setJob(job);
            contact.setAddress(address);
            contact.setEmail(email);
            contact.setSex(sex);
            contact.setFavious(favious);
            contact.setCompany(company);
            contact.setRemarks(remarks);
            contact.setFamilyPhone(familyPhone);
            contact.setMobilePhone(mobilePhone);
            contact.setOfficePhone(officePhone);
            contact.setSortKey(sortKey);
            contact.setSysContactId(sysContactid);
            list.add(contact);
        }
        cursor.close();
        database.close();
        
    }
    
    
//    public class AttentionAdapter extends BaseAdapter{
//        private Context cxt;
//        private List<MyContact> list;
//        private LayoutInflater inflater;
//        
//        public AttentionAdapter(Context cxt, List<MyContact> list){
//            this.cxt = cxt;
//            this.list = list;
//            inflater = LayoutInflater.from(cxt);
//        }
//        
//        @Override
//        public View getView(int position, View convertView, ViewGroup parent) {
//            ViewHolder holder;
//            if(convertView == null){
//                convertView = inflater.inflate(R.layout.attention_item, null);
//                holder = new ViewHolder();
//                holder.name = (TextView) convertView.findViewById(R.id.attentionContactNameId);
//                convertView.setTag(holder);
//            }else{
//                holder = (ViewHolder) convertView.getTag();
//            }
//            holder.name.setText(list.get(position).getName());
//            return convertView;
//        }
//        
//        @Override
//        public int getCount() {
//            return list.size();
//        }
//
//        @Override
//        public Object getItem(int position) {
//            return list.get(position);
//        }
//
//        @Override
//        public long getItemId(int position) {
//            return position;
//        }
//    }
//    
    @Override
    public void onDestroy(){
        if(manager != null){
            manager.close();
        }
        super.onDestroy();
    }
    
    public static class ViewHolder{
        TextView name;
    }

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()) {
		case R.id.contact:
            Intent contactIntent = new Intent();
            contactIntent.setClass(this, MainActivity.class);
            startActivity(contactIntent);
            break;
		case R.id.schedule_and_carlendar:

			Intent intent = new Intent();
			SharedPreferences preferences = getSharedPreferences(
					"scheduleStatusMode", Context.MODE_PRIVATE);
			String lunchMode = preferences.getString(
					"CalendarDefaultLunchMode", "WeekCalendar");
			if (lunchMode.equalsIgnoreCase("DayCalendar")) {
				Date date = new Date();
				SimpleDateFormat sdf = new SimpleDateFormat("yyyy-M-d");
				String currentDate = sdf.format(date); // 当期日期
				String year_c = currentDate.split("-")[0];
				String month_c = currentDate.split("-")[1];
				String day_c = currentDate.split("-")[2];
				Calendar car = Calendar.getInstance();
				car.setTime(new Date());
				ArrayList<String> scheduleDate = makeScheduleDate(year_c,
						month_c, day_c, car.get(Calendar.DAY_OF_WEEK) - 1);
				intent.putStringArrayListExtra("scheduleDate", scheduleDate);
				intent.setClass(this, ScheduleInfoView.class);
			} else if (lunchMode.equalsIgnoreCase("WeekCalendar")) {
				intent.setClass(this, CalendarWeekActivity.class);
			} else if (lunchMode.equalsIgnoreCase("MonthCalendar")) {
				intent.setClass(this, CalendarActivity.class);
			}
			startActivity(intent);
			break;
		case R.id.search_contact_schedule:
			Intent intent_search = new Intent();
			intent_search.setClass(this, SearchActivity.class);
			startActivity(intent_search);
			break;
		case R.id.note_book:
			Intent noteIntent = new Intent();
			noteIntent.setClass(this, NoteBookActivity.class);
			startActivity(noteIntent);
			break;
		}
	}
	
	public ArrayList<String> makeScheduleDate(String scheduleYear,String scheduleMonth,String scheduleDay,int position){
		String week = "";
		//得到这一天是星期几
        switch(position%7){
        case 0:
      	  week = "星期日";
      	  break;
        case 1:
      	  week = "星期一";
      	  break;
        case 2:
      	  week = "星期二";
      	  break;
        case 3:
      	  week = "星期三";
      	  break;
        case 4:
      	  week = "星期四";
      	  break;
        case 5:
      	  week = "星期五";
      	  break;
        case 6:
      	  week = "星期六";
      	  break;
        }
		 
        ArrayList<String> scheduleDate = new ArrayList<String>();
        scheduleDate.add(scheduleYear);
        scheduleDate.add(scheduleMonth);
        scheduleDate.add(scheduleDay);
        scheduleDate.add(week);
        //scheduleDate.add(scheduleLunarDay);
        return scheduleDate;
	}

	@Override
	protected int initLayout() {
		// TODO Auto-generated method stub
		return R.layout.attention_contact_page;
	}

	@Override
	protected View initCustomLayout() {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	protected void initViewCmp() {
		// TODO Auto-generated method stub
		attentionList = (ListView) findViewById(R.id.attentionContactListId);
        add_contacts=(Button)findViewById(R.id.bt_add_contacts);
        add_contacts.setVisibility(View.GONE);
		btn_contact=(Button)findViewById(R.id.contact);
		btn_carlendar=(Button)findViewById(R.id.schedule_and_carlendar);
		btn_search=(Button)findViewById(R.id.search_contact_schedule);
		note_book=(Button)findViewById(R.id.note_book);
		title_bt_setting=(Button)findViewById(R.id.title_bt_setting);
		title_bt_setting.setVisibility(View.GONE);
		btn_attention = (Button)findViewById(R.id.attention_contact);
		btn_attention.setBackgroundResource(R.drawable.home_btn_bg_d);
		((TextView)findViewById(R.id.title_txt)).setText("关注人");
		alpha = (QuickAlphabeticBar)findViewById(R.id.fast_scroller);
		manager = new DatabaseManager(this);
        init();
//        if(list == null || list.isEmpty()){
//            return;
//        }
        setAdapter( list);
        attentionList.setAdapter(adapter);
		
		
	}
	
//	private String[] lianxiren1 = new String[] { "拨打电话", "发送短信", "查看详细", "添加关注", "添加任务", "删除" };
	private String[] lianxiren1 = new String[] { "拨打电话", "发送短信", "查看详细", "取消关注", "添加任务"};

	private void setAdapter(List<MyContact> list) {
		adapter = new AttentionAdapter(this, list, alpha);
		attentionList.setAdapter(adapter);
		alpha.init(ContactAttentionActivity.this);
		alpha.setListView(attentionList);
		alpha.setVisibility(View.VISIBLE);
		attentionList.setOnItemClickListener(new OnItemClickListener() {
			public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
				MyContact cb = (MyContact) adapter.getItem(position);
				showContactDialog(lianxiren1, cb, position);
			}
		});
	}
	public static String[] SMS_COLUMNS = new String[]{  
		"thread_id"
	};
	
	private String getSMSThreadId(String adddress){
		Cursor cursor = null;  
		ContentResolver contentResolver = getContentResolver();  
		cursor = contentResolver.query(Uri.parse("content://sms"), SMS_COLUMNS, " address like '%" + adddress + "%' ", null, null);  
		String threadId = "";
		if (cursor == null || cursor.getCount() > 0){
			cursor.moveToFirst();
			threadId = cursor.getString(0);
			cursor.close();
			return threadId;
		}else{
			cursor.close();
			return threadId;
		}
	}
	//群组联系人弹出页
		private void showContactDialog(final String[] arg ,final MyContact cb, final int position){
			new AlertDialog.Builder(this).setTitle(cb.getName()).setItems(arg,
					new DialogInterface.OnClickListener(){
				public void onClick(DialogInterface dialog, int which){

					Uri uri = null;

					switch(which){

					case 0://打电话
						String toPhone = cb.getMobilePhone();
						uri = Uri.parse("tel:" + toPhone);
						Intent it = new Intent(Intent.ACTION_CALL, uri);
						startActivity(it);
						break;

					case 1://发短息

						String threadId = getSMSThreadId(cb.getMobilePhone());
						
						Map<String, String> map = new HashMap<String, String>();
						map.put("phoneNumber", cb.getMobilePhone());
						map.put("threadId", threadId);
						BaseIntentUtil.intentSysDefault(ContactAttentionActivity.this, MessageBoxList.class, map);
						break;

					case 2:// 查看详细       修改联系人资料
	                    Intent intent2 = new Intent();
					    SQLiteDatabase sqlAction = manager.getWritableDatabase();
					    Cursor cursor = sqlAction.query(DBInitScript.Table_ContactsInfo, null, "contacts_id=" + cb.getContactsId(), null, null, null, null, null);
					    if(cursor == null || cursor.getCount() != 1){
					        break;
					    }
					    //设置为编辑操作
					    intent2.putExtra("edit", true);
					    cursor.moveToFirst();
	                    int index = -1;
	                    index = cursor.getColumnIndex("contacts_id");
	                    intent2.putExtra("contacts_id", cursor.getInt(index));
	                    
	                    index = cursor.getColumnIndex("sys_contactid");
	                    intent2.putExtra("sys_contactid", cursor.getInt(index));
	                    
	                    index = cursor.getColumnIndex("name");
	                    intent2.putExtra("name", cursor.getString(index));
	                    
//	                    index = cursor.getColumnIndex("age");
//	                    intent2.putExtra("age", cursor.getInt(index));
	                    
	                    index = cursor.getColumnIndex("job");
	                    intent2.putExtra("job", cursor.getString(index));
	                    
	                    index = cursor.getColumnIndex("address");
	                    intent2.putExtra("address", cursor.getString(index));
	                    
	                    index = cursor.getColumnIndex("email");
	                    intent2.putExtra("email", cursor.getString(index));
	                    
	                    index = cursor.getColumnIndex("sex");
	                    intent2.putExtra("sex", cursor.getString(index));
	                    
	                    index = cursor.getColumnIndex("favious");
	                    intent2.putExtra("favious", cursor.getString(index));
	                    
	                    index = cursor.getColumnIndex("company");
	                    intent2.putExtra("company", cursor.getString(index));
	                    
	                    index = cursor.getColumnIndex("remarks");
	                    intent2.putExtra("remarks", cursor.getString(index));
	                    
	                    index = cursor.getColumnIndex("family_phone");
	                    intent2.putExtra("family_phone", cursor.getString(index));
	                    
	                    index = cursor.getColumnIndex("office_phone");
	                    intent2.putExtra("office_phone", cursor.getString(index));
	                    
	                    index = cursor.getColumnIndex("mobile_phone");
	                    intent2.putExtra("mobile_phone", cursor.getString(index));
	                    
	                    index = cursor.getColumnIndex("birth_date");
	                    intent2.putExtra("birth_date", cursor.getString(index));
	                    
					    intent2.setClass(ContactAttentionActivity.this, AddNewActivity.class);
					    startActivityForResult(intent2, CONTACT_ADD_EDIT_REQUST_CODE);
					    cursor.close();
					    sqlAction.close();
						break;

					case 3://删除关注
					    deleteAttention(cb);
						break;
					case 4://添加任务
					    Intent intentAdd = new Intent();
					    Calendar c = Calendar.getInstance();
	                    int year = c.get(Calendar.YEAR);
	                    int month = c.get(Calendar.MONTH) + 1;
	                    int day = c.get(Calendar.DAY_OF_MONTH);
	                    String ch_dayOfWeek = DateUtils.getWeek(c.getTime());
	                    ArrayList<String> scheduleDate = new ArrayList<String>();
	                    scheduleDate.add(year + "");
	                    scheduleDate.add(month + "");
	                    scheduleDate.add(day + "");
	                    scheduleDate.add(ch_dayOfWeek);
	                    intentAdd.putStringArrayListExtra("scheduleDate", scheduleDate);
		                SQLiteDatabase sqlAction2 = manager.getWritableDatabase();
	                    Cursor cursor2 = sqlAction2.query(DBInitScript.Table_ContactsInfo, null, "contacts_id=" + cb.getContactsId(), null, null, null, null, null);
	                    if(cursor2 == null || cursor2.getCount() != 1){
	                        break;
	                    }
	                    cursor2.moveToFirst();
	                    int indexAdd = cursor2.getColumnIndex("contacts_id");
	                    intentAdd.putExtra("objectID", String.valueOf(cursor2.getInt(indexAdd)));
	                    indexAdd = cursor2.getColumnIndex("name");
	                    intentAdd.putExtra("objectName", cursor2.getString(indexAdd));
	                    intentAdd.putExtra("operateType", "add");
	                    intentAdd.putExtra("from", "HomeContactActivity");
		                intentAdd.setClass(ContactAttentionActivity.this, ScheduleView.class);
//		                startActivityForResult(intentAdd,0);
		                intentAdd.putExtra("scheduleMode", "0");
		                startActivityForResult(intentAdd, TASK_ADD_REQUEST_CODE);
		                cursor2.close();
		                sqlAction2.close();
					    break;
					case 5:// 删除

						//showDelete(cb.getContactsId(), position);
						break;
					}
				}
			}).show();
		}
	
		
	@Override
	protected void initListener() {
		// TODO Auto-generated method stub
		btn_contact.setOnClickListener(this);
		btn_carlendar.setOnClickListener(this);
		btn_search.setOnClickListener(this);
        note_book.setOnClickListener(this);
	}

	public void deleteAttention(MyContact mc){
	    SQLiteDatabase database = manager.getWritableDatabase();
	    ContentValues values = new ContentValues();
	    values.put("is_attention", 0);
	    database.update(DBInitScript.Table_ContactsInfo, values, "contacts_id=?", new String[]{mc.getContactsId() + ""});
	    database.close();
	    list.remove(mc);
	    adapter.notifyDataSetChanged();
	}
	
	@Override
	protected void initData() {
		// TODO Auto-generated method stub
		
	}

	@Override
	protected void initAsycnData() {
		// TODO Auto-generated method stub
		
	}

	@Override
	protected void changeDefaultSetting() {
		// TODO Auto-generated method stub
		
	}
    
    
    
}
